# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
""" """
import calendar
import datetime
import json
import logging
import os
import socket
from logging import handlers
import datedays
import requests
import yaml
import sys
import os
from dateutil.relativedelta import relativedelta


def get_base_path():
    if getattr(sys, "frozen", False):
        # 打包后的路径（单文件模式下指向临时目录，多文件模式下指向应用程序目录）
        if hasattr(sys, "_MEIPASS"):
            return sys._MEIPASS  # 单文件模式的临时目录
        else:
            return os.path.dirname(sys.executable)  # 应用程序的安装目录（多文件模式）
    else:
        # 开发环境，使用当前脚本的目录
        return os.path.dirname(__file__)


base_path = get_base_path()


def read_config(config_path=r"./config/client_config.yaml"):
    """读取config.yaml配置文件"""
    full_path = os.path.join(base_path, config_path)
    with open(full_path, encoding="utf-8") as f:
        config = yaml.safe_load(f)
    return config


client_config = read_config()
excel_save_dir = client_config.get("保存目录")
client_version = client_config.get("客户端版本号")
server_ip = client_config.get("服务器信息").get("服务器IP")
server_port = client_config.get("服务器信息").get("端口")


def save_config(save_dir, save_file_path=r"./suning_config/client_config.yaml"):
    client_config["保存目录"] = save_dir
    with open(save_file_path, "w", encoding="utf-8") as f:
        yaml.dump(client_config, f, allow_unicode=True)


current_dir = os.getcwd()
log_file_path = os.path.join(current_dir, "logs", "lemon.logs")


def echo_log(log_level: str = "INFO", write_log: bool = False):
    """
    日志格式化打印
    :param log_level: 打印高于等于设定级别的日志。DEBUG < INFO < WARNING < ERROR < CRITICAL
    :param write_log: 是否需要将日志写入到文件
    :return: None
    """
    # 日志文件名及路径
    logger = logging.getLogger()
    logger.setLevel(log_level)
    formatter = logging.Formatter(
        "%(asctime)s [%(levelname)s]: %(message)s", "%Y-%m-%d %H:%M:%S"
    )
    # 控制台打印日志
    stream_handler = logging.StreamHandler()
    stream_handler.setFormatter(formatter)
    logger.addHandler(stream_handler)
    # 日志写文件
    if write_log:
        file_handler = logging.FileHandler(log_file_path, encoding="utf-8")
        logging.handlers.TimedRotatingFileHandler(
            filename=log_file_path, when="D", interval=1
        )
        file_handler.setFormatter(formatter)
        logger.addHandler(file_handler)


echo_log()


def data2beautify(data: (dict, list)):
    """
    字典或列表类型的数据，进行美化输出
    :param data: 字典类型数据
    :return: 格式化数据
    """
    data = json.dumps(data, indent=4, ensure_ascii=False)
    return data


def get_desktop():
    """获取桌面路径"""
    # 获取当前用户的主目录
    home_dir = os.path.expanduser("~")
    # 根据操作系统获取桌面路径
    if os.name == "nt":  # Windows系统
        desktop_path = os.path.join(home_dir, "Desktop")
    elif os.name == "posix":  # macOS 或 Linux系统
        desktop_path = os.path.join(home_dir, "Desktop")
    else:
        desktop_path = ""  # 其他系统或未知系统
    return desktop_path


def get_yes_date(days=1):
    """"""
    yes_date = datedays.getyesterday(days=days)
    return yes_date


def get_yes_start_time(days=1):
    """"""
    yes_date = datedays.getyesterday(days=days)
    yes_start_time = f"{yes_date} 00:00:00"
    return yes_start_time


def get_yes_end_time(days=1):
    """"""
    yes_date = datedays.getyesterday(days=days)
    yes_end_time = f"{yes_date} 23:59:59"
    return yes_end_time


def get_today_start_time():
    today_date = datedays.getyesterday(days=0)
    today_start_time = f"{today_date} 00:00:00"
    return today_start_time


def get_today_end_time():
    today_date = datedays.getyesterday(days=0)
    today_end_time = f"{today_date} 23:59:59"
    return today_end_time


def get_current_month_start():
    """获取这个月第一天，格式YYYY-mm-dd HH:MM:SS"""
    now = datetime.datetime.now().date()
    current_month_start = datetime.datetime(now.year, now.month, 1, 0, 0, 0)
    format_start_time = current_month_start.strftime("%Y-%m-%d %H:%M:%S")
    return format_start_time


def get_last_month():
    """获取上个月，格式YYYYmm"""
    now = datetime.datetime.now()
    last_month_day = datetime.datetime(now.year, now.month, 1) - datetime.timedelta(
        days=1
    )
    last_month = last_month_day.strftime("%Y%m")
    return last_month


def get_last_month_start_end():
    """获取上个月第一天和最后一天，格式YYYY-mm-dd HH:MM:SS"""
    now = datetime.datetime.now().date()
    current_month_start = datetime.datetime(now.year, now.month, 1)
    last_month_end = current_month_start - datetime.timedelta(days=1)
    last_month_start = datetime.datetime(last_month_end.year, last_month_end.month, 1)
    format_start_time = last_month_start.strftime("%Y-%m-%d")
    format_end_time = last_month_end.strftime("%Y-%m-%d")
    last_month_start = f"{format_start_time} 00:00:00"
    last_month_end = f"{format_end_time} 23:59:59"
    return last_month_start, last_month_end


def get_month_start_end_time(year: str, month: str):
    """获取某个月的第一天0点到最后一天23:59:59"""
    year, month = int(year), int(month)
    weekDay, monthCountDay = calendar.monthrange(year, month)
    month_start_date = str(datetime.date(year, month, day=1))
    month_start_time = f"{month_start_date} 00:00:00"
    month_end_date = str(datetime.date(year, month, day=monthCountDay))
    month_end_time = f"{month_end_date} 23:59:59"
    return month_start_time, month_end_time


def get_last_twelve_months() -> list:
    """
    获取最近一年的月份，月份格式YYYYmm
    :return: 从本月开始往前推一年的年月组成的列表
    """
    last_six_months = list()
    for x in range(12):
        month_date = datetime.datetime.now().date() - relativedelta(months=x)
        last_six_months.append(datetime.datetime.strftime(month_date, "%Y%m"))
    return last_six_months


def post_json(url: str, data: dict = None, log_switch: bool = True, **kwargs):
    """
    发送post请求，请求内容为json数据
    :param url: 请求url
    :param data: 请求体
    :param log_switch: 日志开关
    :return: 接口响应
    """
    headers = kwargs.get("headers")
    if headers:
        ...
    else:
        headers = {"Content-Type": "application/json"}
    timeout = kwargs.get("timeout")
    res = requests.post(
        url, data=json.dumps(data), headers=headers, timeout=timeout
    ).json()
    if log_switch:
        logging.info(f"[请求消息]向{url}接口发起POST请求：\n{data2beautify(data)}")
        logging.info(f"[响应消息]从{url}接口收到响应：\n{data2beautify(res)}")
    return res


def get_local_ip():
    """获取本机内网IP"""
    res = socket.gethostbyname(socket.gethostname())
    return res


if __name__ == "__main__":
    print(read_config())
